import React, { Component, PureComponent } from 'react';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import IotUserForm from '@/components/IotUserForm';
import { Card, Divider, Button, Icon, Modal,Form } from 'antd';
import AdvancedSearch from '@/components/AdvancedSearch';
import AdvancedTable from '@/components/AdvancedTable';
import styles from './iotUser.less';
import { deleteById, retrieval} from '@/services/requestData';
import { openNotificationWithIcon, switcher, QueryCond, deleteInvalidSigns } from '@/utils/tools';

/**
 * 用户列表
 * @author 蔡万源 2019-04-24
 */
@connect(({ user_add, loading }) => ({
  user_add,
  loading: loading.effects['models/user/user_add'],
}))
export default class IotUser extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datalines: [],
      loading: false,
      visible: false,
      row: {},

      dicType:{},
      dicGroup:{},

      columnTypeKey:[],
      columnTypeValue:[],
      columnGroupKey:[],
      columnGroupValue:[],
    };
    // 高级检索配置
    this.master = 'iot_user';
    this.items = [
      {  key: 'username',  name: '用户名称',  type: 'input',  first: true,  datatable: this.master,  mode: 3,},
    ];
    // 表格栏目对应字段配置
    this.columns = [
      { title: '用户名', dataIndex: 'username', sorter: true, first: true },
      { title: '用户权限', dataIndex: 'auths', sorter: true, first: true ,render: (val) => {
        return switcher(val,['S','A','U'],['超级管理员','管理员','普通用户'],"其他人员");
      }},
      { title: '操作', dataIndex: '$$operations', render: (row) => {
        return (<div>
          <Button className={styles.buttonCheck} onClick={() => {
              console.log(row);
              this.setState({
                  row:row,
                  visible: true,
                  disabled:true,
              });
          }}>查看</Button>
          <Button className={styles.buttonEdit} onClick={() => {
              let handle = row.getHandle();
              this.setState({
                  row:row,
                  visible: true,
                  disabled:false,
                  handle:handle,
              });
              handle.updateList();
          }}>修改</Button>
          <Button className={styles.buttonDelete} onClick={() => {
              Modal.confirm({
                title: '删除',
                content: '确定要删除该数据吗？',
                onOk() {
                  let response = deleteById("Iot_User",row.id);
                  response.then(content => {
                    openNotificationWithIcon("success","删除成功","恭喜，删除成功！");
                    let handle = row.getHandle();
                    handle.updateList();
                  }).catch(e=>{
                    openNotificationWithIcon("error","加载失败","无法获得数据，请检查信息是否正确");
                  });
                },
                onCancel() {},
              });
          }}>删除</Button>
          </div>);
      } },
    ];
    // 特殊控制按钮配置
    this.controllers = [
      {
        name: '添加',
        icon: 'file',
        callback: handle => {
          this.setState({
            row: {},
            visible: true,
            disabled: false,
            handle: handle,IotUserForm
          });
          handle.updateList();
        },
      },
    ];
  }
  
  componentDidMount(){
    let responseType = retrieval({datatable:"devicetype",conds:[]});
    responseType.then(res=>{
      let dicType = {};
      let columnTypeKey=[];
      let columnTypeValue=[];
      res.forEach(x=>{
        dicType[x.device_type_name]=x.id;
        columnTypeKey.push(x.id);
        columnTypeValue.push(x.device_type_name);
      })
      console.log(dicType);
      this.setState({
        dicType:dicType,
        columnTypeKey:columnTypeKey,
        columnTypeValue:columnTypeValue,
      })      
    }).catch(e=>{
      openNotificationWithIcon("error","数据读取失败","数据读取失败，请确认网络连接是否正常");
    })

    let responseGroup = retrieval({datatable:"devicegroup",conds:[]})
    responseGroup.then(res=>{
      let dicGroup = {};
      let columnGroupKey=[];
      let columnGroupValue=[];
      res.forEach(x=>{
        dicGroup[x.device_group_name]=x.id;
        columnGroupKey.push(x.id);
        columnGroupValue.push(x.device_group_name);
      })
      console.log(dicGroup);
      this.setState({
        dicGroup:dicGroup,
        columnGroupKey:columnGroupKey,
        columnGroupValue:columnGroupValue,
      })   
    }).catch(e=>{
      openNotificationWithIcon("error","数据读取失败","数据读取失败，请确认网络连接是否正常");
    })
  }

  handleSubmit = (err, values) => {
    const { dispatch } = this.props;
    if (!err) {
        // let conds = new QueryCond();
        // conds.exactQuery('username', deleteInvalidSigns(values.username));
        // let searchParam = {datatable:"user",conds:conds.getConds()};
        // let response = retrieval(searchParam)
        // response.then(e=>{
        //   if(e.length>0){
        //     openNotificationWithIcon("error","提交失败","提交失败，列表中已存在该用户！");
        //   }else{
            let form = {};
            let objKeys = Object.keys(values);
            for(var one of objKeys){
              if(typeof values[one] == "object"){
                form[one] = values[one].key;
              }else{
                form[one] = values[one];
              }
            }
            form.id = this.state.row.id;
            console.log(form);
            dispatch({
              type: 'user_add/addUser',
              payload: {
                datatable: "Iot_User",
                body: form,
              },
              callback:()=>{
                let handle = this.state.handle;
                handle && handle.updateList();
              }
            });
            this.setState({visible: false})
        //   }
        // }).catch(e=>{
        //   openNotificationWithIcon("error","提交失败","请检查填写是否正确");
        // })
      }
  };

  showAlert = () => {
    const duration = 3.5;
    if (this.props.user_add.response) {
      let { state } = this.props.user_add.response;
      if (state) {
        openNotificationWithIcon("success","提交成功","恭喜，提交成功！");
      } else {
        openNotificationWithIcon("error","提交失败","提交失败，列表中已存在该用户！");
      }
      this.props.user_add.response = null;
    }
  }

  showWindow = () => {
    const IotUserFormWrapper = Form.create({ name: 'IotUserForm' })(IotUserForm);
    this.showAlert();
    return (
      <Modal
        visible={this.state.visible}
        title="详细"
        width="800px"
        destroyOnClose
        onCancel={() => {
          this.setState({ visible: false });
        }}
        footer={null}
      >
        <div>
          <Card className={styles.selectCard}>
            <IotUserFormWrapper  onSubmit={this.handleSubmit}  disabled={this.state.disabled}  result={this.state.row}/>
          </Card>
        </div>
      </Modal>
    );
  };
  render() {
    return (
      <PageHeaderWrapper>
        {this.showWindow()}
        <Card bordered={true}>
          <AdvancedTable
            columns={this.columns}
            bordered
            // useMultiSelect
            updateFirst
            controllers={this.controllers}
            master={this.master}
            items={this.items}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
